﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using ViewModel;

namespace IssueTracker.CustomControls
{
    public partial class admin : UserControl
    {
        int currentUserId = 0;
        int currentShopId = 0;
        int currentAreaId = 0;
        int currentGroupId = 0;
        public admin()
        {
            InitializeComponent();
        }

        private void admin_Load(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            LoadUserForm();
            Cursor.Current = Cursors.Default;
        }

        private void tabControl1_Selected(object sender, TabControlEventArgs e)
        {
            errorProvider1.Clear();
            Cursor.Current = Cursors.WaitCursor;
            if (tabControl1.SelectedTab == tabPageUser)
            {
                LoadUserForm();
            }
            else if (tabControl1.SelectedTab == tabPageRegisterShop)
            {
                LoadRegisterShopForm();
            }
            else if (tabControl1.SelectedTab == tabPageArea)
            {
                LoadAreaForm();
            }
            else
            {
                LoadGroupForm();
            }
            Cursor.Current = Cursors.Default;
        }

        private void LoadUserForm()
        {
            cmbShop.DataSource = Service.Admin.GetShops();
            cmbShop.DisplayMember = "Name";
            cmbShop.ValueMember = "ID";

            cmbRole.DataSource = Service.Admin.GetRoles();
            cmbRole.DisplayMember = "Name";
            cmbRole.ValueMember = "ID";

            dataGridViewUsers.AutoGenerateColumns = false;
            dataGridViewUsers.DataSource = Service.Admin.GetUsers();
            dataGridViewUsers.ContextMenuStrip = contextMenuStrip1;
        }

        private void LoadRegisterShopForm()
        {
            //bind area drop down list
            cmbArea.DataSource = Service.Admin.GetAreas();
            cmbArea.DisplayMember = "Name";
            cmbArea.ValueMember = "AreaCode";

            //bind group
            cmbGroup.DataSource = Service.Admin.GetGroups();
            cmbGroup.DisplayMember = "Name";
            cmbGroup.ValueMember = "ID";

            dataGridViewShop.AutoGenerateColumns = false;
            dataGridViewShop.DataSource = Service.Admin.GetShops();

            txtShopName.Text = string.Empty;
            txtShopDescription.Text = string.Empty;
            chkArea.Checked = false;
            chkGroup.Checked = false;
        }

        private void LoadAreaForm()
        {
            txtArea.Text = string.Empty;
            txtAreaDescription.Text = string.Empty;
            dataGridViewArea.AutoGenerateColumns = false;
            dataGridViewArea.DataSource = Service.Admin.GetAreas();
        }

        private void LoadGroupForm()
        {
            txtGroup.Text = string.Empty;
            txtGroupDesciption.Text = string.Empty;
            dataGridViewGroup.AutoGenerateColumns = false;
            dataGridViewGroup.DataSource = Service.Admin.GetGroups();
        }

        private void btnShopSave_Click(object sender, EventArgs e)
        {
            //check empty field
            errorProvider1.Clear();
            if (string.IsNullOrEmpty(txtShopName.Text))
            {
                errorProvider1.SetError(txtShopName, "Shop name can not be empty.");
                return;
            }
            else if (string.IsNullOrEmpty(txtShopDescription.Text))
            {
                errorProvider1.SetError(txtShopDescription, "Shop description can not be empty.");
                return;
            }
            //check duplicate shop name
            List<Shop> shops = (List<Shop>)dataGridViewShop.DataSource;
            int chk = shops.Where(x => x.ID != currentShopId && string.Compare(x.Name, txtShopName.Text, true) == 0).Count();
            if (chk > 0)
            {
                errorProvider1.SetError(txtShopName, string.Format("Shop name \"{0}\" already exist. Please choose another name.", txtShopName.Text));
                return;
            }
            Shop obj = new Shop()
            {
                ID = currentShopId,
                Name = txtShopName.Text,
                Area = new Area() { AreaCode = chkArea.Checked ? cmbArea.SelectedValue.ToString() : "" },
                Group = new Group() { ID = chkGroup.Checked ? Convert.ToInt32(cmbGroup.SelectedValue) : 0 },
                UDF1 = txtShopDescription.Text
            };
            Cursor.Current = Cursors.WaitCursor;
            chk = Service.Admin.SaveShop(obj);
            currentShopId = 0;
            LoadRegisterShopForm();
            Cursor.Current = Cursors.Default;
        }

        private void btnAreaSave_Click(object sender, EventArgs e)
        {
            errorProvider1.Clear();
            //check area name empty
            if (string.IsNullOrEmpty(txtArea.Text))
            {
                errorProvider1.SetError(txtArea, "Area name can not be empty.");
                return;
            }
            else if (string.IsNullOrEmpty(txtAreaDescription.Text))
            {
                errorProvider1.SetError(txtAreaDescription, "Area description can not be empty.");
                return;
            }
            //check area name already exist
            List<Area> areas = (List<Area>)dataGridViewArea.DataSource;
            int chk = areas.Where(x => x.ID != currentAreaId && string.Compare(x.Name, txtArea.Text, true) == 0).Count();
            if (chk > 0)
            {
                errorProvider1.SetError(txtArea, string.Format("Area name \"{0}\" already exist. Plese try new area name.", txtArea.Text));
                return;
            }
            ViewModel.Area obj = new ViewModel.Area();
            obj.ID = currentAreaId;
            obj.Name = txtArea.Text;
            obj.Description = txtAreaDescription.Text;
            Cursor.Current = Cursors.WaitCursor;
            chk = Service.Admin.SaveArea(obj);

            currentAreaId = 0;
            LoadAreaForm();
            Cursor.Current = Cursors.Default;
        }

        private void btnGroupSave_Click(object sender, EventArgs e)
        {
            errorProvider1.Clear();
            if (string.IsNullOrEmpty(txtGroup.Text))
            {
                errorProvider1.SetError(txtGroup, "Group name can not be empty.");
                return;
            }
            else if (string.IsNullOrEmpty(txtGroupDesciption.Text))
            {
                errorProvider1.SetError(txtGroupDesciption, "Group description can not be empty.");
                return;
            }
            List<Group> groups = (List<Group>)dataGridViewGroup.DataSource;
            int chk = groups.Where(x => x.ID != currentGroupId && string.Compare(x.Name, txtGroup.Text, true) == 0).Count();
            if (chk > 0)
            {
                errorProvider1.SetError(txtGroup, string.Format("Group name \"{0}\" already exist. Please try new group name.", txtGroup.Text));
                return;
            }

            ViewModel.Group obj = new ViewModel.Group();
            obj.ID = currentGroupId;
            obj.Name = txtGroup.Text;
            obj.Description = txtGroupDesciption.Text;
            Cursor.Current = Cursors.WaitCursor;
            chk = Service.Admin.SaveGroup(obj);
            LoadGroupForm();
            Cursor.Current = Cursors.Default;
        }

        private void dataGridViewGroup_CellValueNeeded(object sender, DataGridViewCellValueEventArgs e)
        {
            if (e.RowIndex >= 0 && e.ColumnIndex == 0)
                e.Value = e.RowIndex + 1;
        }

        private void chkGroup_CheckStateChanged(object sender, EventArgs e)
        {
            if (chkGroup.Checked)
                cmbGroup.Enabled = true;
            else
                cmbGroup.Enabled = false;
        }

        private void chkArea_CheckedChanged(object sender, EventArgs e)
        {
            if (chkArea.Checked)
                cmbArea.Enabled = true;
            else
                cmbArea.Enabled = false;
        }

        private void btnSaveUser_Click(object sender, EventArgs e)
        {
            lblUserMessage.Visible = false;
            //chkeck empty field
            errorProvider1.Clear();
            if (string.IsNullOrEmpty(txtUserName.Text))
            {
                errorProvider1.SetError(txtUserName, "Username can not be empty.");
                return;
            }
            if (string.IsNullOrEmpty(txtPassword.Text))
            {
                errorProvider1.SetError(txtPassword, "Password can not be empty");
                return;
            }

            //save data
            Member obj = new Member()
            {
                ID = currentUserId,
                UserName = txtUserName.Text,
                Password = txtPassword.Text,
                Role = (Role)cmbRole.SelectedValue,
                Shop = (Shop)cmbShop.SelectedItem
            };
            Cursor.Current = Cursors.WaitCursor;
            int chk = Service.Admin.SaveUser(obj);
            if (chk > 0)
            {
                lblUserMessage.Text = "Success";
                lblUserMessage.ForeColor = Color.Green;
                dataGridViewUsers.AutoGenerateColumns = false;
                dataGridViewUsers.DataSource = Service.Admin.GetUsers();
            }
            else
            {
                lblUserMessage.Text = "Fail";
                lblUserMessage.ForeColor = Color.Red;
            }
            currentUserId = 0;
            lblUserMessage.Visible = true;
            Cursor.Current = Cursors.Default;
        }

        private void editToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (tabControl1.SelectedTab == tabPageUser)
            {
                if (dataGridViewUsers.SelectedRows.Count > 0)
                {
                    currentUserId = (int)dataGridViewUsers.SelectedRows[0].Cells["ID"].Value;
                    txtUserName.Text = dataGridViewUsers.SelectedRows[0].Cells["UserName"].Value.ToString();
                    txtPassword.Text = dataGridViewUsers.SelectedRows[0].Cells["Password"].Value.ToString();
                    cmbRole.Text = dataGridViewUsers.SelectedRows[0].Cells["Role"].Value.ToString();
                    cmbShop.Text = dataGridViewUsers.SelectedRows[0].Cells["Shop"].Value.ToString();
                }
                else
                    currentUserId = 0;
            }
            else if (tabControl1.SelectedTab == tabPageRegisterShop)
            {
                if (dataGridViewShop.SelectedRows.Count > 0)
                {
                    currentShopId = (int)dataGridViewShop.SelectedRows[0].Cells["Shop_ID"].Value;
                    txtShopName.Text = string.Format("{0}", dataGridViewShop.SelectedRows[0].Cells["ShopName"].Value);
                    if (dataGridViewShop.SelectedRows[0].Cells["ShopArea"].Value != null)
                    {
                        chkArea.Checked = true;
                        cmbArea.Text = string.Format("{0}", dataGridViewShop.SelectedRows[0].Cells["ShopArea"].Value);
                    }
                    else
                        chkArea.Checked = false;

                    if (dataGridViewShop.SelectedRows[0].Cells["ShopGroup"].Value != null)
                    {
                        chkGroup.Checked = true;
                        cmbGroup.Text = string.Format("{0}", dataGridViewShop.SelectedRows[0].Cells["ShopGroup"].Value);
                    }
                    else chkGroup.Checked = false;
                    txtShopDescription.Text = string.Format("{0}", dataGridViewShop.SelectedRows[0].Cells["ShopDescription"].Value);
                }
                else
                    currentShopId = 0;
            }
            else if (tabControl1.SelectedTab == tabPageArea)
            {
                if (dataGridViewArea.SelectedRows.Count > 0)
                {
                    currentAreaId = (int)dataGridViewArea.SelectedRows[0].Cells["Area_ID"].Value;
                    txtArea.Text = dataGridViewArea.SelectedRows[0].Cells["Area"].Value.ToString();
                    txtAreaDescription.Text = dataGridViewArea.SelectedRows[0].Cells["Area_Description"].Value.ToString();
                }
                else
                    currentAreaId = 0;
            }
            else if (tabControl1.SelectedTab == tabPageGroup)
            {
                if (dataGridViewGroup.SelectedRows.Count > 0)
                {
                    currentGroupId = (int)dataGridViewGroup.SelectedRows[0].Cells["Group_ID"].Value;
                    txtGroup.Text = dataGridViewGroup.SelectedRows[0].Cells["Group"].Value.ToString();
                    txtGroupDesciption.Text = dataGridViewGroup.SelectedRows[0].Cells["Group_Description"].Value.ToString();
                }
                else
                    currentGroupId = 0;
            }
        }

        private void deleteToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (tabControl1.SelectedTab == tabPageUser)
            {
                if (dataGridViewUsers.SelectedRows.Count > 0)
                {
                    DialogResult dlg = MessageBox.Show("You are going to delete user " + dataGridViewUsers.SelectedRows[0].Cells["UserName"].Value.ToString() + " ", "Are you sure?", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                    if (dlg == DialogResult.Yes)
                    {
                        currentUserId = (int)dataGridViewUsers.SelectedRows[0].Cells["ID"].Value;
                        Service.Admin.DeleteUser(currentUserId);
                        LoadUserForm();
                    }
                }
                currentUserId = 0;
            }
            else if (tabControl1.SelectedTab == tabPageRegisterShop)
            {
                if (dataGridViewShop.SelectedRows.Count > 0)
                {
                    DialogResult dlg = MessageBox.Show("You are going to delete shop " + dataGridViewShop.SelectedRows[0].Cells["ShopName"].Value.ToString() + " ", "Are you sure?", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                    if (dlg == DialogResult.Yes)
                    {
                        currentShopId = (int)dataGridViewShop.SelectedRows[0].Cells["Shop_ID"].Value;
                        Service.Admin.DeleteShop(currentShopId);
                        LoadRegisterShopForm();
                    }
                }
                currentShopId = 0;
            }
            else if (tabControl1.SelectedTab == tabPageArea)
            {
                if (dataGridViewArea.SelectedRows.Count > 0)
                {
                    DialogResult dlg = MessageBox.Show("You are going to delete area " + dataGridViewArea.SelectedRows[0].Cells["Area"].Value.ToString() + " ", "Are you sure?", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                    if (dlg == DialogResult.Yes)
                    {
                        currentAreaId = (int)dataGridViewArea.SelectedRows[0].Cells["Area_ID"].Value;
                        Service.Admin.DeleteArea(currentAreaId);
                        LoadAreaForm();
                    }
                }
                currentAreaId = 0;
            }
            else if (tabControl1.SelectedTab == tabPageGroup)
            {
                if (dataGridViewGroup.SelectedRows.Count > 0)
                {
                    DialogResult dlg = MessageBox.Show("You are going to delete group " + dataGridViewGroup.SelectedRows[0].Cells["Group"].Value.ToString() + " ", "Are you sure?", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                    if (dlg == DialogResult.Yes)
                    {
                        currentGroupId = (int)dataGridViewGroup.SelectedRows[0].Cells["Group_ID"].Value;
                        Service.Admin.DeleteGroup(currentGroupId);
                        LoadGroupForm();
                    }
                }
                currentGroupId = 0;
            }
        }
    }
}
